import { useCallback, useMemo } from "react"
import { useNavigate } from "react-router-dom"
import { useModalSlideUp } from "@/features/useModal"
import { useAtom } from "jotai"
import { SetVerifyAtom, verifyAtom } from "@/pages/AccountPage/atoms/verify"
import ResetPassword from "@/pages/AccountPage/components/Models/ResetPassword"
import { createLogger } from "@/utils/logger"
import { PATHS } from "@/constants/path"
import kycRequiredMethods from "@/features_signal/kycRequiredMethods"
import kycController from "@/features_signal/kycController"

const logger = createLogger("useCard")

export type KycStatus = Kyc.Status

interface UseCardProps {
    userInfo: ApiTypes.Fetcher.Result.NewUserInfo
}

export function useCard({ userInfo }: UseCardProps) {
    const navigate = useNavigate()
    const { open: openModal } = useModalSlideUp("account-page")
    const [verifyData] = useAtom(verifyAtom)
    const [, setVerifyData] = useAtom(SetVerifyAtom)

    // Memoized values
    const hasLoginPassword = useMemo(
        () => userInfo?.has_login_password ?? userInfo?.hasLoginPassword,
        [userInfo?.has_login_password, userInfo?.hasLoginPassword],
    )
    const hasEmail = useMemo(() => userInfo?.has_email, [userInfo?.has_email])

    const emailValue = useMemo(() => {
        return userInfo?.has_email ? userInfo.email : "Set"
    }, [userInfo?.has_email, userInfo?.email])

    const phoneNumberValue = useMemo(() => {
        console.log("phoneNumberValue....detail", userInfo)
        const hasPhone = userInfo?.has_phone_number ?? userInfo?.hasPhoneNumber
        if (!hasPhone) return "Set"
        return `+${userInfo.country_code} ${userInfo.phone}`
    }, [userInfo])

    const passwordValue = useMemo(() => {
        const hasPassword = userInfo?.has_login_password ?? userInfo?.hasLoginPassword
        return hasPassword ? "Change" : "Set"
    }, [userInfo?.has_login_password, userInfo?.hasLoginPassword])

    // Handlers
    const handleUserName = useCallback(() => {
        // if (editable) {
        navigate("form/username")
        // }
    }, [navigate])

    const handleEmailClick = useCallback(() => {
        if (hasEmail) {
            //目前结论是没有邮箱可以设置，有邮箱了就不可以修改
            // openModal(
            //     <ChangInfo
            //         value={userInfo?.email || ""}
            //         type="email"
            //     />,
            //     {
            //         closeOnClickMask: false,
            //         closeOnEscape: false,
            //     },
            // )
        } else {
            navigate("/s-account/form/email")
            logger.debug("Navigate to email form")
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [hasEmail, userInfo?.email, navigate])

    //手机号不让修改
    // const handlePhoneClick = useCallback(() => {
    //     openModal(
    //         <ChangInfo
    //             value={phoneNumberValue}
    //             type="phone"
    //         />,
    //         {
    //             closeOnClickMask: false,
    //             closeOnEscape: false,
    //         },
    //     )
    // }, [phoneNumberValue, openModal])
    const handlePhoneClick = () => {
        return
    }

    const handlePassword = useCallback(() => {
        if (hasLoginPassword) {
            openModal(<ResetPassword />, {
                closeOnClickMask: true,
                closeOnEscape: false,
            })
            setVerifyData({
                ...verifyData,
                field: "password",
                type: "edit",
            })
        } else {
            setVerifyData({
                ...verifyData,
                field: "password",
                type: "create",
            })
            navigate("/s-account/form/password")
        }
    }, [hasLoginPassword, openModal, setVerifyData, verifyData, navigate])

    const getKYCContent = useCallback(() => {
        const statusMap: Record<KycStatus, unknown> = {
            unset: {
                rightButton: {
                    text: "Go To Verify",
                    onClick: () => {
                        kycController.navigateToKyc()
                    },
                },
            },
            basic_passed: {
                rightButton: {
                    text: "Go To Verify",
                    onClick: () => {
                        kycController.navigateToKyc()
                    },
                },
            },
            draft: {
                value: "Draft",
                showArrow: false,
            },
            pending: {
                value: "Pending...",
                showArrow: false,
            },
            approved: {
                value: "Certified",
                showArrow: false,
            },
            rejected: {
                value: "Rejected",
                onClick: () => {
                    logger.debug("show rejected reason")
                },
                showArrow: true,
            },
            final_rejected: {
                value: "Blocked",
                showArrow: false,
            },
        }

        return statusMap[kycRequiredMethods.kycStatus.peek()] || statusMap.unset
    }, [navigate])

    const kycContent = useMemo(() => {
        return getKYCContent()
    }, [getKYCContent])

    return {
        hasLoginPassword,
        hasEmail,
        emailValue,
        phoneNumberValue,
        passwordValue,
        kycContent,
        handleUserName,
        handleEmailClick,
        handlePhoneClick,
        handlePassword,
    }
}
